package cn.sunxiansheng.exception;

import cn.sunxiansheng.tool.response.ResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static cn.sunxiansheng.tool.constant.HttpStatus.BAD_REQUEST;
import static cn.sunxiansheng.tool.constant.HttpStatus.ERROR;

/**
 * 全局异常处理器
 *
 * @author sunxiansheng
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理 JSON 请求体参数校验失败JSR303 (MethodArgumentNotValidException)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultWrapper<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        log.error("参数校验失败: {} | 异常详情: ", message, e);
        return ResultWrapper.fail(BAD_REQUEST, message);
    }

    /**
     * 处理表单或查询参数校验失败 (BindException)
     */
    @ExceptionHandler(BindException.class)
    public ResultWrapper<Object> handleBindException(BindException e) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        log.error("参数绑定失败: {} | 异常详情: ", message, e);
        return ResultWrapper.fail(BAD_REQUEST, message);
    }

    /**
     * 处理自定义业务异常 (CustomException)
     */
    @ExceptionHandler(CustomException.class)
    public ResultWrapper<Object> handleCustomException(CustomException e) {
        log.error("自定义异常: {} | 错误码: {} | 异常详情: ", e.getErrorMessage(), e.getErrorCode(), e);
        return ResultWrapper.fail(e.getErrorCode(), e.getErrorMessage());
    }

    /**
     * 捕获所有未处理的系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultWrapper<Object> handleException(Exception e) {
        log.error("系统异常: {} | 异常详情: ", e.getMessage(), e);
        return ResultWrapper.fail(ERROR, "系统异常");
    }
}